package com.ymtms.applicationsystem.exception;

import com.ymtms.applicationsystem.vo.ResultUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * @auther: autumn-luo
 * @description:
 * @createTime: 2019-10-26 22:52
 */
@Log4j2
@RestControllerAdvice
@Component
public class GlobalEmpExceptionHandler {

    /*
     * @createTime 2019-10-28 16:10
     * @author autumn-luo
     * @param: ex
     * @return:
     * @description: 后端验证参数异常获取
     */
    @ExceptionHandler()
    @ResponseBody
    public ResultUtil bindExceptionHandler(BindException ex) {

        ex.printStackTrace();
        //处理返回的错误信息
        StringBuffer errorMsg = new StringBuffer();
        BindException c = (BindException) ex;
        List<ObjectError> errors = c.getBindingResult().getAllErrors();
        for (ObjectError error : errors) {
            errorMsg.append(error.getDefaultMessage()).append(";");
        }
        // 日志打印
        log.error(errorMsg.toString());
        return ResultUtil.error(-1, errorMsg.toString());
    }


    /*
     * @createTime 2019-10-28 16:58
     * @author autumn-luo
     * @return:
     * @description: 自定义职员异常处理
     */
    @ExceptionHandler()
    @ResponseBody
    public ResultUtil empExceptionHandler(EmpException eex) {
        eex.printStackTrace();
        StringBuffer errorMsg = new StringBuffer();
        String errors = eex.getMessage();
        log.error(errors);
        return ResultUtil.error(-1, errors);
    }
    /*
     * @createTime 2019-10-28 16:58
     * @author autumn-luo
     * @return:
     * @description: 自定义异常处理
     */
    @ExceptionHandler()
    @ResponseBody
    public ResultUtil wageExceptionHandler(WageException wex) {
        wex.printStackTrace();
        StringBuffer errorMsg = new StringBuffer();
        String errors = wex.getMessage();
        log.error(errors);
        return ResultUtil.error(-1, errors);
    }
}
